<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工艺编码" prop="tecId">
        <el-input
          v-model="queryParams.tecId"
          placeholder="请输入工艺编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工艺名称" prop="tecName">
        <el-input
          v-model="queryParams.tecName"
          placeholder="请输入工艺名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:tec:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:tec:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:tec:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:tec:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tecList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="工艺id" align="center" prop="id" />
      <el-table-column label="工艺编码" align="center" prop="tecId" />
      <el-table-column label="工艺名称" align="center" prop="tecName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="HandleExamine(scope.row)"

          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:tec:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:tec:remove']"
          >删除</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工艺对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :before-close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="工艺编码" prop="tecId">
          <el-input v-model="form.tecId" placeholder="请输入工艺编码" :readonly="!isVisible"/>
        </el-form-item>
        <el-form-item label="工艺名称" prop="tecName">
          <el-input v-model="form.tecName" placeholder="请输入工艺名称" :readonly="!isVisible"/>
        </el-form-item>

        <el-divider>工 序 列 表</el-divider>
        <el-button v-if="isVisible" style="margin-bottom: 10px;" type="primary" @click="processadd">添 加</el-button>
        <el-card shadow="always" style="border-radius: 15px;">
          <el-table style="border-radius: 15px;" v-loading="loading" border :data="form.mtrs">
            <el-table-column label="工序" align="center" prop="mtrName" >
              <template slot-scope="scope" >
                <el-select :style="{ width: !isVisible ? '595px' : null }" v-model="scope.row.id" filterable placeholder="请选择"
                           @change="(option) => mtrchang(option, scope.$index)" :disabled="!isVisible" >
<!--                  :label为组件的显示文本，:value为组件的实际值-->
                  <el-option v-for="item in processselectoption" :key="item.id" :label="item.processId" :value="item.id">
                  </el-option>
<!--                  <el-option v-else v-for="item in proselectoption" :key="item.id" :label="item.proId" :value="item.id">-->
<!--                  </el-option>-->
                </el-select>
              </template>
            </el-table-column>
<!--            <el-table-column label="原料编码" align="center" prop="mtrCode"/>-->
<!--            <el-table-column label="原料价格" align="center" prop="cost">-->
<!--              <template slot-scope="scope">-->
<!--                {{ scope.row.cost==undefined?'0元':scope.row.cost+'元' }}-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column label="数量" align="center" class-name="small-padding fixed-width">-->
<!--              <template slot-scope="scope">-->
<!--                <a-input-number id="inputNumber" v-model:value="scope.row.mtrQuantity" :min="0" :precision="0"/>-->
<!--              </template>-->
<!--            </el-table-column>-->

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="isVisible">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="processadd(scope.$index, scope.row)"
                           v-hasPermi="['mes:proinfo:edit']">增加</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="processdel(scope.$index)"
                           v-hasPermi="['mes:proinfo:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-card>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="isVisible">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTec, getTec, delTec, addTec, updateTec } from "@/api/system/tec";
import {listDevice} from "@/api/system/device";
import {listProcess} from "@/api/system/process";
import {addPro, editTecPro, fetchProcessIdsByTechId, listPro, listTecPro, updatePro} from "@/api/system/pro";

export default {
  name: "Tec",
  data() {
    return {
      //测试数据工序
      textTecId:'ddy111',

      //渲染条件
      isVisible:false,

      //区分开修改和增加，不同的条件渲染不同的el-option   true:添加，false：修改
      //addoredit:true,
      //工艺的工序下拉框数据
      processselectoption:[],
      //工艺工序
      proselectoption:[],
      //工艺拥有的工序
      protec:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工艺表格数据
      tecList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tecId: null,
        tecName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tecId: [
          { required: true, message: "工艺编码不能为空", trigger: "blur" }
        ],
        tecName: [
          { required: true, message: "工艺名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  // watch: {
  //   'form.tecId'(newVal, oldVal) {
  //     if (newVal !== oldVal) {
  //       // 在这里处理值改变后的逻辑
  //       this.form.tecId = newVal;
  //     }
  //   }
  // },

  created() {
    this.getList();
  },
  methods: {
    /**
     * 下拉框改变
     * @param {选项值} option
     */
    mtrchang(option, index) {
    //ID不同，查的表不同
      let ss = this.processselectoption.find(item => item.id == option) //item.id不对。查工序表里面的id和传入的参数option进行对比，显然不对，工序表里面的id和工序表里面的processid显然不对
      // this.form.proId = ss.processId
      // this.form.tecId = ss.tecId
      console.log(ss)
    if(ss) {
      //this.form.mtrs[index].id = ss.id //!!!!!!!!!!删了这个id值就会不对   这个id为工序表里头的id，不为工艺工序表里头的id
      this.form.mtrs[index].proId = ss.processId
      // console.log(ss.processId + "111" + ss.proId)
      console.log("processId:" + ss.processId)

      // // this.form.mtrs[index].processId = ss.processId
      this.form.mtrs[index].tecId = this.form.tecId
    }
      // this.form.mtrs[index].processName = ss.processName
      // this.form.mtrs[index].tecId = this.form.tecId

      // this.form.mtrs[index].mtrCode = ss.mtrCode
      // this.form.mtrs[index].cost = ss.cost
    },
    /**
     * 删除原料
     * @param {下标} index
     */
    processdel(index) {
      this.form.mtrs.splice(index, 1)
    },
    /**
     * 添加原料
     * @param {下标} index
     * @param {行数据} row
     */
    processadd(index, row) {
      if (index != undefined) {
        this.form.mtrs.splice(index + 1, 0,
          {
            // createBy: "",
            // createTime: "",
            // updateBy: "",
            // updateTime: null,
            // remark: null,
            // id: null,
            // houId: null,
            // mtrCode: null,
            // processName: null,
            // mtrQuantity: 0,
            // mtrProType: 0
          }
          )
      } else {
        this.form.mtrs.push(
          {
            // createBy: "",
            // createTime: "",
            // updateBy: "",
            // updateTime: null,
            // remark: null,
            // id: null,
            // houId: null,
            // mtrCode: null,
            // processName: null,
            // mtrQuantity: 0,
            // mtrProType: 0
          }
          )
      }
    },
    // processadd(index, row) {
    //   if (this.form.mtrs) {
    //     if (index !== undefined) {
    //       console.log("定义")
    //       this.form.mtrs.splice(index + 1, 0, {
    //         // 新元素的属性
    //       });
    //     } else {console.log("中间")
    //       this.form.mtrs.push({
    //         // 新元素的属性
    //       });
    //     }
    //   } else {console.log("未定义")
    //     this.form.mtrs = []; // 如果数组未定义，则初始化为空数组
    //
    //   }
    // },

    /** 查询工艺列表 */
    getList() {
      this.loading = true;
      listTec(this.queryParams).then(response => {
        this.tecList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      //工序列表
      listProcess().then((res) => {
        this.processselectoption = res.rows
        console.log("🚀 ~ file: index.vue:240 ~ listProinfo ~ this.proinfoselectoption:", this.processselectoption)
      });
      //查工艺工序列表
      listPro().then((res) => {
        this.proselectoption = res.rows
        console.log("🚀 ~ file: index.vue:240 ~ listProinfo ~ this.proselectoption:", this.proselectoption)
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isVisible = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tecId: null,
        tecName: null,
        oldTecId:null,
        mtrs: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isVisible = true;
      this.open = true;
      this.title = "添加工艺";
    },
    /** 根据工艺编码获取所有工序*/
    getProcess(){
      console.log("当前工艺：" + this.form.tecId)
      //let tecproArray = this.proselectoption.filter(item => item.tecId == this.form.tecId);//let tecpro = this.proselectoption.find(item => item.tecId == this.form.tecId)

      // if(tecproArray.length > 0){
      //
      //   this.form.mtrs = tecproArray

        //其实只要这个id值就够了，若工序表里面有这个id，就显示这个id值对应的proid
        // this.form.mtrs = [
        //   {
        //     "id": 19,
        //     "proId": "gx20",
        //     "tecId": "gy"
        //   },
        //   {
        //     "id": 22,
        //     "proId": "工序",
        //     "tecId": "gy"
        //   }
        // ]

        //根据工艺Id去查看工艺包含的所有工序
        fetchProcessIdsByTechId(this.form.tecId).then((res) =>{
          this.protec = res.data
          console.log("🚀 ~ file: index.vue:240 ~ listProinfo ~ this.protec:", this.protec)
        });
        this.form.mtrs =this.protec
    },
    /**
     * 查看按钮操作 */
    HandleExamine(row) {
      this.reset();
      this.isVisible = false;
      const id = row.id || this.ids
      getTec(id).then(response => {
        this.form = response.data;
        this.form.oldTecId = this.form.tecId;

        //根据工艺Id去查看工艺包含的所有工序
        fetchProcessIdsByTechId(this.form.tecId).then((res) =>{
          this.protec = res.data;
          //(Q1：这里的位置不对，会导致第一次点击修改按钮得到的数据不对)
          this.form.mtrs =this.protec

          this.open = true;
          this.title = "查看工艺";

        });
      });
    },
    /**
     * 修改按钮操作 */
    handleUpdate(row) {
      console.log("修改按钮" + this.form.tecId)
      this.reset();
      this.isVisible = true;
      console.log("修改按钮表单重置后" + this.form.tecId)
      const id = row.id || this.ids
      getTec(id).then(response => {
        this.form = response.data;
        this.form.oldTecId = this.form.tecId;

        //根据工艺Id去查看工艺包含的所有工序
        fetchProcessIdsByTechId(this.form.tecId).then((res) =>{
          this.protec = res.data;
          //(Q1：这里的位置不对，会导致第一次点击修改按钮得到的数据不对)
          this.form.mtrs =this.protec

          this.open = true;

          this.title = "修改工艺";

        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      // this.isVisible = false;
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form)
          if (this.form.mtrs.findIndex(e => { return e.id == null }) != -1 || this.form.mtrs.length == 0) {
            this.$modal.msgError("请添加工序或将工序信息填写完整");
          } else {
          if (this.form.id != null) {

              //this.form.oldTecId = this.form.tecId;

            console.log("oldTecId:" + this.form.oldTecId);

            let lprotec = this.protec.map(item => {
              return this.processselectoption.find(option => option.id === item.id);
            });


            console.log(this.form);
            this.form.mtrs = lprotec.map(item => {
              return { id: item.id, proId: item.processId, tecId: this.form.tecId};
            });


            updateTec(this.form).then(response => {
            this.$modal.msgSuccess("修改工艺成功");
            this.open = false;
            this.getList();
            return editTecPro(this.form);
            })
            // console.log("oldTecId:" + this.form.oldTecId);
            // console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" + this.form.tecId);
            .then(response => {
              this.$modal.msgSuccess("修改工艺工序成功");
            })
            .catch(error => {
              if (error && (error.message === "工序编码重复" || (error.response && error.response.data && error.response.data.message === "工序编码重复"))) {
                this.$modal.msgError("修改工艺失败，工艺编码编码重复");
                this.reset();
              } else {
                console.error("发生错误:", error);
                this.$modal.msgError("修改工艺或工艺工序时发生错误");
              }
            });

          } else {
            // addTec(this.form).then(response => {
            //   this.$modal.msgSuccess("新增工艺成功");
            //   this.open = false;
            //   this.getList();
            // });
            //
            // addPro(this.form).then(response => {
            //   this.$modal.msgSuccess("新增工艺工序成功");
            //   this.open = false;
            //   this.getList();
            // });

            addTec(this.form).then(response => {
              this.$modal.msgSuccess("新增工艺成功");
              this.open = false;
              this.getList();
              return addPro(this.form);
            })
            .then(response => {
            this.$modal.msgSuccess("新增工艺工序成功");
            })
            .catch(error => {
                if (error && (error.message === "工艺编码重复" || (error.response && error.response.data && error.response.data.message === "工艺编码重复"))) {
                this.$modal.msgError("新增工艺失败，工艺编码编码重复");
                this.reset();
                } else {
                console.error("发生错误:", error);
                this.$modal.msgError("新增工艺或工艺工序时发生错误");
                }
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除工艺编号为"' + ids + '"的数据项？').then(function() {
        return delTec(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/tec/export', {
        ...this.queryParams
      }, `tec_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
